﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Web.Mvc;
using DataTables;
using LookupField.Services;
using MvcSiteMapProvider;
using Newtonsoft.Json;
using WindMill.Models.Cadastro;
using WindMill.Models.Controladoria;
using WindMill.Models.Estoque;
using Mensagem = WindMill.Models.Estoque.Mensagem;

namespace WindMill.Controllers
{
    public class ClasseController : Controller
    {
        private ILookupService lookupService;

        private EDMEstoque db = new EDMEstoque();

        public ClasseController(ILookupService lookupService)
        {
            this.lookupService = lookupService;
        }

        // GET: /Classe/
        [MvcSiteMapNode(Title = "Estoque", Key = "Estoque",ParentKey = "Home", Description = "icon-home", Clickable = false)]
        [MvcSiteMapNode(Title = "Classes", Key="Classes", ParentKey = "Estoque", Description = "icon-home")]                
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Search(JQueryDataTablesModel jQueryDataTablesModel)
        {

            var search = jQueryDataTablesModel.sSearch.ToUpper();
            var query = db.Classes.Where(c => c.DescClasse.ToUpper().Contains(search));
            var columns = jQueryDataTablesModel.GetSortedColumns();
            
            foreach (var c in columns)
            {
                var parameter = Expression.Parameter(typeof(Classe));
                var memberExpression = Expression.Property(parameter,c.PropertyName);
                var lambdaExpression = Expression.Lambda(memberExpression, parameter);
                LambdaExpression untyped = lambdaExpression;

                if(c.Direction == SortingDirection.Ascending)
                    query = Queryable.OrderBy(query, (dynamic) untyped);    
                else
                    query = Queryable.OrderByDescending(query, (dynamic)untyped);    
            }
                            
            var totalRecordCount = db.Classes.Count();
            var searchRecordCount = query.Count();
            
            query = query.Skip(jQueryDataTablesModel.iDisplayStart).Take(jQueryDataTablesModel.iDisplayLength);


            return Json(new JQueryDataTablesResponse<Classe>(
                items: query.ToList(),
                totalRecords: totalRecordCount,
                totalDisplayRecords: searchRecordCount,
                sEcho: jQueryDataTablesModel.sEcho));
        }

        //[HttpPost]       
        public JsonResult Lookup(string field, string value)
        {        

            Type t = null;
            var lookupField = "";
            var displayField = "";
            ObjectContext context = null;
            switch (field)
            {
                case "CodRamo":
                    t = typeof(Ramo);
                    lookupField = "Id";
                    displayField = "Descricao";
                    context =  ((IObjectContextAdapter)new EDMCadastro()).ObjectContext;
                    break;
                case "CodMensagem":
                    t = typeof (Mensagem);
                    lookupField = "CodMensagem";
                    displayField = "DescMensagem";
                    context = ((IObjectContextAdapter)db).ObjectContext;;
                    break;
                case "CodContaContabil":
                    t = typeof(PlanoConta);
                    lookupField = "NumPlanoConta";
                    displayField = "DescPlanoConta";
                    context = ((IObjectContextAdapter)new EDMControladoria()).ObjectContext;
                    break;
            }

            return lookupService.Search(t, lookupField, displayField, value, context);
        }
        
        
        // GET: /Classe/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Classe classe = db.Classes.Find(id);
            if (classe == null)
            {
                return HttpNotFound();
            }
            return View(classe);
        }


        
        // GET: /Classe/Create
        [MvcSiteMapNode(Title = "Adicinar Classe", Key = "AddClasses", ParentKey = "Estoque", Description = "icon-plus")]
        public ActionResult Create()
        {
            var lista = new[]
                {
                    new {Cod = "00", Valor = ""}, new {Cod = "00", Valor = "00 - Mercadoria para revenda"},
                    new {Cod = "01", Valor = "01 - Matéria Prima"},
                    new {Cod = "02", Valor = "02 - Embalagem"},
                    new {Cod = "03", Valor = "03 - Produto em processo"},
                    new {Cod = "04", Valor = "04 - Produto acabado"},
                    new {Cod = "05", Valor = "05 - Subproduto"},
                    new {Cod = "06", Valor = "06 - Produto intermediário"},
                    new {Cod = "07", Valor = "07 - Material de uso e consumo"},
                    new {Cod = "08", Valor = "08 - Ativo imobilizado"},
                    new {Cod = "09", Valor = "09 - Serviços"},
                    new {Cod = "10", Valor = "10 - Outros insumos"},
                    new {Cod = "99", Valor = "99 - Outros"},
                };

            ViewBag.IndTipos = new SelectList(lista, "Cod", "Valor");

            return View();
        }

        // POST: /Classe/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="CodClasse,DescClasse,PercComissao1,PercComissao2,NumClasse,NumSubclasse,PercCusto,ValCusto,CodRamo,IndTipo,CodLoteTipo,CodMensagem,CodContaContabil")] Classe classe)
        {
            if (ModelState.IsValid)
            {
                db.Classes.Add(classe);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.CodMensagem = new SelectList(db.Mensagens, "CodMensagem", "DescMensagem", classe.CodMensagem);
            return View(classe);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult CreateAjax([Bind(Include = "CodClasse,DescClasse,PercComissao1,PercComissao2,NumClasse,NumSubclasse,PercCusto,ValCusto,CodRamo,IndTipo,CodLoteTipo,CodMensagem,CodContaContabil")] Classe classe)
        {
            if (ModelState.IsValid)
            {
                db.Classes.Add(classe);
                db.SaveChanges();
                return Json("Index");
            }

            ViewBag.CodMensagem = new SelectList(db.Mensagens, "CodMensagem", "DescMensagem", classe.CodMensagem);
            return Json(classe);
        }

        // GET: /Classe/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var lista = new[]
                {
                    new {Cod = "00", Valor = ""}, new {Cod = "00", Valor = "00 - Mercadoria para revenda"},
                    new {Cod = "01", Valor = "01 - Matéria Prima"},
                    new {Cod = "02", Valor = "02 - Embalagem"},
                    new {Cod = "03", Valor = "03 - Produto em processo"},
                    new {Cod = "04", Valor = "04 - Produto acabado"},
                    new {Cod = "05", Valor = "05 - Subproduto"},
                    new {Cod = "06", Valor = "06 - Produto intermediário"},
                    new {Cod = "07", Valor = "07 - Material de uso e consumo"},
                    new {Cod = "08", Valor = "08 - Ativo imobilizado"},
                    new {Cod = "09", Valor = "09 - Serviços"},
                    new {Cod = "10", Valor = "10 - Outros insumos"},
                    new {Cod = "99", Valor = "99 - Outros"},
                };

            ViewBag.IndTipos = new SelectList(lista, "Cod", "Valor");

            Classe classe = db.Classes.Find(id);
            if (classe == null)
            {
                return HttpNotFound();
            }
            ViewBag.CodMensagem = new SelectList(db.Mensagens, "CodMensagem", "DescMensagem", classe.CodMensagem);
            return View(classe);
        }

        // POST: /Classe/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="CodClasse,DescClasse,PercComissao1,PercComissao2,NumClasse,NumSubclasse,PercCusto,ValCusto,CodRamo,IndTipo,CodLoteTipo,CodMensagem,CodContaContabil")] Classe classe)
        {
            if (ModelState.IsValid)
            {
                db.Entry(classe).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.CodMensagem = new SelectList(db.Mensagens, "CodMensagem", "DescMensagem", classe.CodMensagem);
            return View(classe);
        }

        // GET: /Classe/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Classe classe = db.Classes.Find(id);
            if (classe == null)
            {
                return HttpNotFound();
            }
            return View(classe);
        }

        // POST: /Classe/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Classe classe = db.Classes.Find(id);
            db.Classes.Remove(classe);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
